#!/usr/bin/perl -w

#################################
# License GPLv2
# Version 1, Oct 2009
# iNextStation@gmail.com
#################################

my @in;
my $out = "out.qif";

###########Begin main#############
sub main() {
	while ($opt = shift(@ARGV)) {
		($opt eq '-in')?	(push(@in, shift(@ARGV))):
		($opt eq '-out')?	($out = shift(@ARGV)):
		($opt eq '-help')?	& help:
					& help;
	} # END while
	
	open OUT, "> $out" or die "Failed to open $out for output.\n";
	
	foreach my $infile (@in) {
		print 'Processing ', $infile, "\n";
		& proc_file($infile);
	} # END foreach
	
	close OUT;
} ###########End main##############


#############BEGIN proc_file()#####
sub proc_file() {
	my $file = $_[0];
	open IN, $file or die "Failed to open file $file\n";
	while (<IN>) {
		if (/消费/ || /;还款/ || /手续/ || /年费/) {
			my $date = get_block($_, ';', ';', 1);
			my $desc2 = get_block($_, ';', ';', 2);
			my $mt = get_block($_, ';', ';', 3);
			my $total = get_block($_, ';', ';', 4);
			my $desc = get_block($_, ';', ';', 5);
	
			my $lline = '';
			if ($desc2 eq '消费') {
				$lline = 'Expenses:不明支出';
				$total = '-'.$total;
			} elsif (index($desc2, '还款') >= 0) {
				$lline = 'Assets:Current Assets:Cash in Wallet';
			} elsif (index($desc2, '年费') >= 0) {
				$lline = 'Expenses:Fees:银行卡年费';
				$total = '-'.$total;
			} elsif (index($desc2, '手续费') >= 0) {
				$lline = 'Expenses:Fees:手续费';
				$total = '-'.$total;
			} # END if
				
			print OUT <<__END__;
!Type:Bank
D$date
T$total
P$desc
L$lline
^
__END__

		} # END if
	} # END while

	close IN;
} ###########END proc_file()################

#########Begin sub help()#################
sub help() {
	print <<__HELP__;
$0 -in <in file1> [-in <in file2>] ... -out <out file> -help
__HELP__
	exit 1;
} ###########END help()#####################

##############Begin get_block()###########
# param: 
# 	<String>line
#	<String>start_pattern
#	<String>end_pattern
#	<int>#
##########################################
sub get_block {
	my $tmp_len = length ($_[1]);
	my $block_start = 0;
	for (my $i = 0; $i < $_[3]; $i++) {
		$block_start =  index ($_[0], $_[1], $block_start) + $tmp_len;
	}

	if ($block_start < $tmp_len) {
		""
	} else {
		my $block_len = index ($_[0], $_[2], $block_start) - $block_start;
		substr ($_[0], $block_start, $block_len);
	}
} ###########END get_block()################

main;
